//
//  GYPayViewController.m
//  GoodLuck
//
//  Created by apple on 2018/4/8.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYPayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "GYNetWorkTools.h"
#import "WXApi.h"
@interface GYPayViewController ()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation GYPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"确认支付";
    
    //监听是微信否支付成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WeiXinPaySuccess) name:WeiXinPaySuccess object:nil];
    
    //监听微信支付取消
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WeiXinPayCancel) name:WeiXinPayCanacel object:nil];
    
    //监听支付宝是否支付成功
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(zhifubaoPaySuccess:) name:zhifubaoPaySuccess object:nil];
    
    [self launchPay];
}

- (void)WeiXinPayCancel {
    NSLog(@"微信支付取消...");
    if (self.orderPay) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (void)WeiXinPaySuccess {
    NSLog(@"微信支付成功回调...");
    self.navigationItem.title = @"支付成功";
    
    [GYNetWorkTools requestWeiXinPaySuccess:self.pay_sn payment_code:self.model.payment_code wxpay_appid:[self.model.payment_config objectForKey:@"wxpay_appid"] wxpay_mch_id:[self.model.payment_config objectForKey:@"wxpay_mch_id"] wxpay_key:[self.model.payment_config objectForKey:@"wxpay_key"] notifyUrl:self.notifyUrl success:^(NSDictionary *obj) {
        //NSLog(@"obj========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *data = [obj objectForKey:@"datas"];
        if (code == 200) {
            if (self.orderPay) {
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }else if (code == 400) {
            NSLog(@"error==========%@",[data objectForKey:@"error"]);
            [EasyTextView showText:@"支付失败,请重新支付!"];
            if (self.orderPay) {
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"支付失败,请重新支付!"];
        if (self.orderPay) {
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        NSLog(@"WeiXinPaySuccesFailed======%@",error);
    }];
    
    //这里要返回订单查询界面或则 上平界面
}

- (void)zhifubaoPaySuccess:(NSNotification *)noti {
    NSLog(@"支付宝支付成功回调");
    NSDictionary *payResult = noti.object;
    int resultStatus = [[payResult objectForKey:@"resultStatus"] intValue];
    if (resultStatus == 9000) {
        //代表支付成功
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[[payResult objectForKey:@"result"] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *alipay_trade_app_pay_response = [result objectForKey:@"alipay_trade_app_pay_response"];
        NSString *trade_no = [alipay_trade_app_pay_response objectForKey:@"trade_no"];
        NSString *out_trade_no = [alipay_trade_app_pay_response objectForKey:@"out_trade_no"];
        
        [GYNetWorkTools requestZhifubaoPaySuccess:out_trade_no trade_no:trade_no uccess:^(NSDictionary *obj) {
            NSLog(@"obj========%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                NSLog(@"支付宝支付完成通知完成!");
                if (self.orderPay) {
                    [self.navigationController popViewControllerAnimated:YES];
                }else {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
            }else {
                NSLog(@"支付宝支付完成通知有误!");
            }
        } error:^(NSError *error) {
            NSLog(@"支付宝支付完成通知有误!");
            if (self.orderPay) {
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }];
    }else {
        //代表支付失败
        if (self.orderPay) {
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

//发起支付
- (void)launchPay {
    if ([self.model.payment_id intValue] == 1) {
        NSLog(@"支付宝支付....");
        //[EasyLodingView showLodingText:@"正在加载..."];
        [GYNetWorkTools requestLaunchPay:self.pay_sn payment_code:self.model.payment_code success:^(NSDictionary *obj) {
            //NSLog(@"zhifubao  =======%@",obj);
            //[EasyLodingView hidenLoding];
            
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                NSString *datas = [obj objectForKey:@"datas"];
                [[AlipaySDK defaultService] payOrder:datas fromScheme:@"zhifubao" callback:^(NSDictionary *resultDic) {
                    NSLog(@"resultDic====%@",resultDic);
                }];
            }else if (code == 400) {
                [EasyTextView showText:@"支付失败请,请重新支付!"];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"支付失败请,请重新支付!"];
            [self.navigationController popViewControllerAnimated:YES];
            [EasyLodingView hidenLoding];
            NSLog(@"LaunchPayzhifubaoFailed=====%@",error);
        }];
    }else if ([self.model.payment_id intValue] == 2) {
        //NSLog(@"微信支付....");
        [GYNetWorkTools requestWeiXinPay:self.pay_sn payment_code:self.model.payment_code wxpay_appid:[self.model.payment_config objectForKey:@"wxpay_appid"] wxpay_mch_id:[self.model.payment_config objectForKey:@"wxpay_mch_id"] wxpay_key:[self.model.payment_config objectForKey:@"wxpay_key"] notifyUrl:self.notifyUrl success:^(NSDictionary *obj) {
            //NSLog(@"obj----=====%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                PayReq *request = [[PayReq alloc] init];
                request.partnerId = [datas objectForKey:@"partnerid"];
                request.prepayId= [datas objectForKey:@"prepayid"];
                request.package = [datas objectForKey:@"package"];
                request.nonceStr= [datas objectForKey:@"noncestr"];
                request.timeStamp= (UInt32)[[datas objectForKey:@"timestamp"] longLongValue];
                request.sign= [datas objectForKey:@"sign"];
                [WXApi sendReq:request];
            }else {
                NSLog(@"error======%@",[[datas objectForKey:@"error"] objectForKey:@"return_msg"]);
            }
        } error:^(NSError *error) {
            NSLog(@"WeiXinPayError");
        }];
    }
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"url=======%@",request.URL);
    __weak GYPayViewController *weakSelf = self;
    BOOL isPay = [[AlipaySDK defaultService] payInterceptorWithUrl:request.URL.description fromScheme:@"GoodLuck" callback:^(NSDictionary *resultDic) {
        NSLog(@"resultDic====%@",resultDic);
        // isProcessUrlPay 代表 支付宝已经处理该URL
        if ([resultDic[@"isProcessUrlPay"] boolValue]) {
            // returnUrl 代表 第三方App需要跳转的成功页URL
            NSString* urlStr = resultDic[@"returnUrl"];
            NSLog(@"urlStr=======%@",urlStr);
            [weakSelf loadWithUrlStr:urlStr];
        }
    }];
    if (isPay) {
        return NO;
    }
    return YES;
}

- (void)loadWithUrlStr:(NSString*)urlStr
{
    if (urlStr.length > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSURLRequest *webRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]
                                                        cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                    timeoutInterval:30];
            [self.webView loadRequest:webRequest];
        });
    }
}

@end
